<template>
  <v-md-editor
    :modelValue="modelValue"
    @update:modelValue="modelValue = $event"
    :v-model="modelValue"
    :height="height + 'px'"
    :disabled-menus="[]"
    :include-level="[1, 2, 3, 4, 5, 6]"
    @upload-image="handleUploadImage"
    @change="change"
  ></v-md-editor>
</template>

<script setup>
import VMdEditor from "@kangc/v-md-editor";
import "@kangc/v-md-editor/lib/style/base-editor.css";
import githubTheme from "@kangc/v-md-editor/lib/theme/github.js";
import "@kangc/v-md-editor/lib/theme/style/github.css";
import { getCurrentInstance, ref, onBeforeMount } from "vue";

// highlightjs
import hljs from "highlight.js";

const { proxy } = getCurrentInstance();

VMdEditor.use(githubTheme, {
  Hljs: hljs,
});

// 接收父组件数据
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  }
})

// 编辑器大小控制
let height=ref()
onBeforeMount(()=>{
  window.innerHeight>500?height.value=window.innerHeight-294:height.value=500
})
window.onresize=()=>{
  if(window.innerHeight>500){
    height.value=window.innerHeight-294
  }
}

const emit = defineEmits();
// 内容改变触发
const change = (markdownContent, htmlContent) => {
  emit("update:modelValue", markdownContent);
  emit("htmlContent", htmlContent);
}

// 图片上传
const handleUploadImage = async (event, insertImage, files) => {
  let result = await proxy.Request({
    url: "file/uploadImage",
    dataType: "file",
    params: {
      file: files[0],
      type: 1,
    }
  });

  if (!result) {
    proxy.$message.error("图片上传失败")
    return;
  }

  const url = proxy.imageUrl + result.data.fileName;
  insertImage({
    url: url,
    desc: '图片',
  });
}
</script>